package com.ycc.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ycc.config.JwtAuthenticationToken;
import com.ycc.model.entity.Result;
import com.ycc.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final ObjectMapper objectMapper;

    public JwtAuthenticationFilter(JwtUtil jwtUtil) {
        this.objectMapper = new ObjectMapper();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String header = request.getHeader("Authorization");
        // 获取请求路径
        String uri = request.getRequestURI();
        log.info("Request URI: {}", uri);
        if (uri.contains("/wxlogin")) {
            filterChain.doFilter(request, response);
            return;
        }
        if (header != null && header.startsWith("Bearer ")) {
            String token = header.substring(7);
            try {
                if (JwtUtil.isTokenExpired(token)) {
                    throw new AuthenticationServiceException("Token已过期");
                }
                Claims claims = JwtUtil.parseToken(token);
                // 将JWT令牌的信息解析为一个Authentication对象，并将其存储到Spring Security的上下文中
                Authentication authentication = new JwtAuthenticationToken(claims);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (ExpiredJwtException e) {
                setFailureResponse(request, response, "Token已过期");
                return;
            } catch (AuthenticationServiceException e) {
                setFailureResponse(request, response, e.getMessage());
                return;
            } catch (Exception e) {
                setFailureResponse(request, response, "身份验证失败");
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private void setFailureResponse(HttpServletRequest request, HttpServletResponse response, String message) throws IOException {
        request.setAttribute("filter.error.message", message);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json;charset=UTF-8"); // Ensure the response content type supports UTF-8
        Result<String> apiResponse = new Result<>(HttpServletResponse.SC_UNAUTHORIZED, message, null);
        response.getWriter().write(objectMapper.writeValueAsString(apiResponse));
    }
}
